# coding=utf-8
# 全世界最帅的帅哥
import json
from flask_restful import reqparse
from ysgg1_club_comment.modules.subject_category import SubjectCategory
from ysgg1_club_comment.modules import db
from flask import current_app, request
from sqlalchemy.exc import SQLAlchemyError, OperationalError
from ysgg1_club_comment.utils.camel_to_snake import camel_to_snake
from ysgg1_club_subject.comment.enums.result_enum import ResultEnum
from sqlalchemy import and_


def get_all_categories():
    try:
        request_json = request.json
        category_type = 1
        category_list = (SubjectCategory.query.
                         with_entities(SubjectCategory.id, SubjectCategory.category_name, SubjectCategory.image_url)
                         .filter(
            and_(SubjectCategory.parent_id == 0, SubjectCategory.category_type == category_type,
                 ~SubjectCategory.is_delete)
        ).all())

        data = []
        for category in category_list:
            data.append(
                {
                    "categoryName": category.category_name,
                    "categoryId": category.id,
                    "imageUrl": category.image_url
                }
            )

        return {"code": 200, "message": "查询成功", "data": data}
    except (SQLAlchemyError, OperationalError, Exception) as e:
        current_app.logger.error(json.dumps(e))
        return {"code": 500, "message": "哦豁, 发生未知的错误咯!", }


def get_category(category_id):
    category = SubjectCategory.query.filter_by(id=category_id).first()
    if category:
        data = {
            "categoryName": category.category_name,
            "categoryId": category.id,
            "imageUrl": category.image_url
        }
        return {"code": 200, "message": "查询成功", "data": data}
    else:
        return {"code": 500, "message": "wrong category_id, please deliver true request"}


def query_category_list():
    try:
        request_json = request.json
        category_type = request_json.get('categoryType') if request_json.get('categoryType') else 1
        category_id = request_json.get('categoryId') if request_json.get('categoryId') else 0
        if not category_id:
            return {"code": 500, "message": "分类id不能为空"}
        category_list = SubjectCategory.query.with_entities(SubjectCategory.id, SubjectCategory.category_name,
                                                            SubjectCategory.image_url).filter(
            and_(SubjectCategory.parent_id == category_id, SubjectCategory.category_type == category_type,
                 ~SubjectCategory.is_delete)).all()

        data = []
        for category in category_list:
            data.append(
                {
                    "categoryName": category.category_name,
                    "categoryId": category.id,
                    "imageUrl": category.image_url
                }
            )

        return {"code": 200, "message": "查询成功", "data": data}
    except (SQLAlchemyError, OperationalError, Exception) as e:
        current_app.logger.error(json.dumps(e.__str__()))
        return {"code": 500, "message": "哦豁, 发生未知的错误咯!", }


def add_category():
    parser = reqparse.RequestParser()
    # 校验(非必须，可以前端校验)
    # 如果有特定的规则 参数可以带type 自行定义校验规则
    parser.add_argument("categoryName", required=True, help="刷题名字不能为空")
    parser.add_argument("categoryType", required=True, help="刷题类别不能为空")
    parser.add_argument("parentId", required=True, help="刷题父级id不能为空")
    parser.add_argument("imgUrl", required=False)

    args = parser.parse_args()
    category_name = args["categoryName"]
    category_type = int(args["categoryType"])
    parent_id = int(args["parentId"])
    img_url = args["imgUrl"]
    try:
        subject_category = SubjectCategory(category_name=category_name, category_type=category_type,
                                           parent_id=parent_id, image_url=img_url)
        db.session.add(subject_category)
        db.session.commit()

        current_app.logger.info("新增刷题成功")
        return {"success": True, "code": 200, "message": "成功"}
    except OperationalError as e:
        current_app.logger.error(json.dumps(e))
        return {"error": e}
    except SQLAlchemyError as e:
        db.session.rollback()
        dict_category = {"categoryName": category_name, "categoryType": category_type, "parentId": parent_id,
                         "imageUrl": img_url}
        json_category = json.dumps(dict_category)
        current_app.logger.error(f"新增刷题失败 {json.dumps(e)} " + json_category)

        return {"success": False, "code": 500, "message": "失败"}


def update_category(category_id):
    request_data = request.json
    category = SubjectCategory.query.filter(and_(
        SubjectCategory.id == category_id, ~SubjectCategory.is_delete)).first()
    if not category:
        return {"code": 200, "message": "请传入正确的分类ID", "data": 0}
    try:
        for key, value in request_data.items():
            # key是驼峰型的变量 categoryName 但是数据库中存的是category_name
            key = camel_to_snake(key)
            if hasattr(category, key):
                setattr(category, key, value)
        db.session.commit()
        current_app.logger.info("修改分类信息成功")
        return {"code": 200, "message": "success!", "count": 1}
    except OperationalError as e:
        current_app.logger.error(json.dumps(e))
        return {"error": e}
    except SQLAlchemyError as e:
        db.session.rollback()
        current_app.logger.error(f"新增刷题失败 {e.__str__()}")
        return {"success": False, "code": 500, "message": "失败"}


def delete_category(category_id):
    try:
        category = SubjectCategory.query.filter(and_(
            SubjectCategory.id == category_id, ~SubjectCategory.is_delete)).first()
        if category:
            category.is_delete = True
            db.session.commit()
            current_app.logger.info("删除分类成功")
            return {"code": ResultEnum.success.code, "message": ResultEnum.success.description, "data": 1}
        current_app.logger.info("删除分类失败, 传入错误的ID")
        return {"code": ResultEnum.fail.code, "message": ResultEnum.fail.description}

    except Exception as e:
        current_app.logger.error(json.dumps(e))
        return {"code": 500, "message": "删除分类失败, 请稍后重试", "data": 0}
